package br.edu.ufabc.gtrnp.helppo.business;

import java.util.List;

import org.hibernate.Session;

import br.edu.ufabc.gtrnp.helppo.business.exception.LoginInvalidoException;
import br.edu.ufabc.gtrnp.helppo.persistence.entity.Usuario;
import br.edu.ufabc.gtrnp.helppo.util.PasswordHelper;

public class LoginBusiness {
	private static LoginBusiness business = new LoginBusiness();

	private LoginBusiness() {
	}

	public static LoginBusiness getInstance() {
		return business;
	}

	@SuppressWarnings("unchecked")
	public Usuario validar(String primeiroNome, String ultimoNome, String senha)
			throws LoginInvalidoException {

		GenericDAO dao = new GenericDAO();
		Session session = dao.getCurrentSession();

		String passwordTratado = PasswordHelper.encrypted(senha);
		StringBuilder builder = new StringBuilder();
		builder.append("FROM Usuario WHERE username = '").append(primeiroNome);
		builder.append("' AND lastname='").append(ultimoNome);
		builder.append("' AND passwordHash='").append(passwordTratado).append("'");

		List<Usuario> usuarios = (List<Usuario>) session.createQuery(builder.toString()).list();
		if (usuarios.size() <= 0) {
			throw new LoginInvalidoException();
		}
		
		Usuario usuario = usuarios.get(0);
		usuario.setPasswordDecrypted(senha);
		
		return usuarios.get(0);
	}

	public Usuario buscaUsuario(String nome, String sobreNome){
		
		GenericDAO dao = new GenericDAO();
		Session session = dao.getCurrentSession();

		StringBuilder builder = new StringBuilder();
		builder.append("FROM Usuario WHERE username = '").append(nome);
		builder.append("' AND lastname='").append(sobreNome).append("'");
		
		Usuario usuario = (Usuario)session.createQuery(builder.toString()).uniqueResult();
		
		return usuario;
	}

}
